package com.baizhi.realm;

import com.baizhi.dao.AdminDAO;
import com.baizhi.entity.Admin;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 自定义AuthenRealm类继承AuthenticatingRealm并重写doGetAuthenticationInfo方法
 * 目的：读取数据库的信息
 */
public class AuthenRealm extends AuthenticatingRealm {
    @Autowired
    private AdminDAO adminDAO;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//        从token中获取用户输入的账号
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
//        根据用户名去数据库中查找对应的用户数据
        Admin admin = adminDAO.selectOne(username);
        if (admin!=null){
            /**
             * SimpleAccount
             * 参数1 数据库中的账号
             * 参数2 数据库查询的密码
             * 参数3 当前对象的名字
             */
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
            session.setAttribute("login",admin);
            return new SimpleAccount(admin.getUsername(),admin.getPassword(),this.getName());
        }
        return null;
    }
}
